package com.iwinding.ladygg.modle.db.impl;

import android.content.Context;
import android.text.TextUtils;

import com.iwinding.ladygg.modle.db.DBHelper;
import com.iwinding.ladygg.modle.db.bean.Login;
import com.iwinding.ladygg.modle.db.dao.LoginDao;

import java.util.List;

/**
 * Created by 82218 on 2017/6/22.
 */

public class LoginDBHelper extends DBHelper implements DBHelper.ILoginHelper{

    private static LoginDBHelper loginDBHelper;

    private LoginDao loginDao;

    private LoginDBHelper(Context context) {
        loginDao = DBHelper.getSession(context).getLoginDao();
    }

    public static LoginDBHelper getInstance(Context context) {
        if (loginDBHelper == null) {
            loginDBHelper = new LoginDBHelper(context);
        }
        return loginDBHelper;
    }

    @Override
    public void updateOrInsertAccount(Login user) {
        if(user == null || TextUtils.isEmpty(user.getUserId())){
            return;
        }
        List<Login> list = loginDao.queryBuilder().where(LoginDao.Properties.UserId.eq(user.getUserId())).list();
        if(list == null || list.size() == 0){
            loginDao.insert(user);
        }else {
            Login update = list.get(0);
            update(update,user);
            loginDao.update(update);
        }
    }

    @Override
    public Login queryLastAccount() {
        List<Login> list = loginDao.queryBuilder().orderDesc(LoginDao.Properties.Id).list();
        if(list != null || list.size() != 0){
            return list.get(0);
        }
        return null;
    }

    private void update(Login oldLogin,Login newLogin){
        oldLogin.setGroupId(newLogin.getGroupId());
        oldLogin.setHeadImg(newLogin.getHeadImg());
        oldLogin.setIsBindingPhone(newLogin.getIsBindingPhone());
        oldLogin.setMobile(newLogin.getMobile());
        oldLogin.setName(newLogin.getName());
        oldLogin.setNickName(newLogin.getNickName());
        oldLogin.setPassword(newLogin.getPassword());
        oldLogin.setUname(newLogin.getUname());
        oldLogin.setUserId(newLogin.getUserId());
    }

}
